// export const http = () => {
//   console.log("hello world")
// }
import { Host } from "./setting";

function showMsg(msg, fn) {
    wx.showModal({
        title: '提示',
        showCancel: false,
        confirmText: "我知道了",
        content: msg || '发生错误，一年后修理',
        success(res) {
            if (res.confirm && fn) {
                fn();
            } else if (res.cancel) {
                console.log('用户点击取消')
            }
        }
    });
};

function http(url, data = {}, method) {
    return new Promise(function(resolve, reject) {
        wx.request({
            method: method || "POST",
            timout: 180000,
            url: Host + url, //仅为示例，并非真实的接口地址
            data,
            header: {
                //'token': wx.getStorageSync('token'),
                'Authorization': wx.getStorageSync('token'),
                'content-type': 'application/json' // 默认值
            },
            success(res) {
                let resp = res.data;
                if (res.statusCode > 400) {
                    reject("发生错误，一年后修理");
                    return
                }
                if (resp.code != 200) {
                    switch (resp.code) {
                        case 401:
                            showMsg(resp.msg, () => {
                                wx.clearStorageSync();
                                wx.reLaunch({ url: '/pages/login/index' });
                            });
                            break;
                        default:
                            console.error(resp.msg)
                            break;
                    }
                    wx.hideLoading();
                    reject(resp.msg || '发生错误，一年后修理');
                } else {
                  let tokenData = res.data
                    if (tokenData.data && tokenData.data.token) { 
                      wx.setStorageSync('token', "Bearer " + tokenData.data.token); 
                    };
                    resolve(res.data)
                }
            },
            fail(error) {
                reject(error);
            }
        })
    })

}

module.exports = {
    http
}